package com.sdry.web.controller.jyy;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Identifyingcode;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.Warehouse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sdry.model.jyy.Receive;
import com.sdry.model.jyy.ReceiveDetail;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.jyy.ReceiveService;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.WarehouseService;
import com.sdry.service.tdd.OthersService;
import com.sdry.utils.BaseUtils;
import com.sdry.utils.DateJsonValueProcessor;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;
/**
 *
 *@ClassName: ReceiveController
 *@Description: 收货计划
 *@Author jyy
 *@Date 2019-04-18 09:35:01
 *@version 1.0
 *修改记录： LZ2019年11月11日 16:53:18在66行和302行新增warehouse_id
*/
@Controller
@RequestMapping("/receive")
public class ReceiveController{
	@Resource ReceiveService ReceiveService;
	
	@Resource
	ReceiveDetailService ReceiveDetailService;
	@Resource
	OthersService othersService;
	@Resource
	WarehouseService warehouseService;
	@Resource
	MaterielService materielService;
	@Resource
	CancellingStockDetailService cancellingStockDetailService;
	public static Logger logger = LogManager.getLogger(ReceiveController.class);
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public Receive queryById(Long id) {
		Receive param = ReceiveService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<Receive> queryAllByMution(HttpSession session, Receive param) {
		//LZ新增仓库id字段
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		param.setWarehouse_id(warehouse_id);
		List<Receive> list = ReceiveService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list")
	public void list(Receive param, HttpSession session, HttpServletResponse response) throws Exception{
		//LZ新增仓库id字段
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		param.setWarehouse_id(warehouse_id);
		param.setIsSimple("0");
		/*
		 * 条件分页查询内容
		 */
		List<Receive> list = ReceiveService.findPageByMution(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = ReceiveService.selectCountByMution(param);
		/*
		 * 转为json数据传至页面
		 */
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		//创建result
		JSONObject result = new JSONObject();
		//转json数据
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		//添加入result
		result.put("code", 0);
		result.put("data", jsonArray);
		result.put("count", total);
		ResponseUtil.write(response, result);
	}
	
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list_return")
	public void list_return(Receive param, HttpSession session, HttpServletResponse response) throws Exception{
		//LZ新增仓库id字段
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		param.setWarehouse_id(warehouse_id);
		param.setIsSimple("0");
		/*
		 * 条件分页查询内容
		 */
		List<Receive> list = ReceiveService.findPageByMutionReturn(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = ReceiveService.selectCountByMutionReturn(param);
		/*
		 * 转为json数据传至页面
		 */
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		//创建result
		JSONObject result = new JSONObject();
		//转json数据
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		//添加入result
		result.put("code", 0);
		result.put("data", jsonArray);
		result.put("count", total);
		ResponseUtil.write(response, result);
	}
	
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert")
	public void insert( HttpSession httpSession, Receive param, HttpServletResponse response) throws Exception{
		//LZ新增仓库id字段
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		//获取当前操作人
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		param.setCreateDate(DateUtil.dateFormat3());
		param.setCreateName(userName);
		param.setState(0);
		param.setWarehouse_id(warehouse_id);
		param.setIsSimple("0");
		
		Long id = ReceiveService.insert(param);
		response.getWriter().print(id);
	}
	
	/** 
	 * 条码入库的发货退回
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert_return")
	public void insert_return( HttpSession httpSession, Receive param, HttpServletResponse response) throws Exception{
		//LZ新增仓库id字段
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		//获取当前操作人
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		param.setCreateDate(DateUtil.dateFormat1());
		//param.setCreateDate(DateUtil.dateFormat3());
		param.setCreateName(userName);
		param.setState(0);
		param.setWarehouse_id(warehouse_id);
		param.setIsSimple("0");
		Long id = ReceiveService.insert_return(param);
		response.getWriter().print(id);
	}

	/**
	 * 电线的收货新增
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/insertLineReceive")
	public void insertLineReceive( HttpSession httpSession, Receive param, HttpServletResponse response) throws Exception{
		//LZ新增仓库id字段
		Long warehouse_id = (Long) httpSession.getAttribute("warehouse_id");
		//获取当前操作人
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();

		param.setCreateDate(DateUtil.dateFormat3());
		param.setCreateName(userName);
		param.setState(0);
		param.setWarehouse_id(warehouse_id);
		param.setIsSimple("0");

		Long id = ReceiveService.insertLineReceive(param);
		response.getWriter().print(id);
	}
	
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/update")
	public void update(Receive param,HttpServletResponse response) throws Exception{
		Integer count = ReceiveService.update(param);
		response.getWriter().print(count);
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(HttpSession httpSession,String ids,HttpServletResponse response) throws Exception{
		/*ids=ids.replace("'",""); 
		Integer count = ReceiveService.delete(ids);
		response.getWriter().print(count);*/
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        //System.out.println(df.format(new Date()));
        ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		String[] arr = ids.split(",");
		
		for (String s : arr) {
			Map map = new HashMap();
			map.put("id", Long.valueOf(s));
			map.put("cancellation_time", df.format(new Date()));
			map.put("cancellation", userName);
			Integer affact = ReceiveService.cacel(map);
			ResponseUtil.write(response, affact);
			map = null;
		}
	}
	
	/** 
	 * 单据合并
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	 * @throws Exception 
	*/
	@RequestMapping("/merge")
	public void merge(HttpSession httpSession, String ids, String receiveNumber, HttpServletResponse response){
		int i = ReceiveService.merge(httpSession, ids, receiveNumber);
		try {
			ResponseUtil.write(response, i);
		} catch (Exception e) {
			e.printStackTrace();
		}
        
	}
	
	@RequestMapping("/restor")
	public void delet(HttpSession httpSession,String ids,HttpServletResponse response) throws Exception{
		/*ids=ids.replace("'",""); 
		Integer count = ReceiveService.delete(ids);
		response.getWriter().print(count);*/
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        //System.out.println(df.format(new Date()));
        ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		String[] arr = ids.split(",");
		
		for (String s : arr) {
			Map map = new HashMap();
			map.put("id", Long.valueOf(s));
			map.put("restorer_time", df.format(new Date()));
			map.put("restorer", userName);
			Integer affact = ReceiveService.restor(map);
			ResponseUtil.write(response, affact);
			map = null;
		}
	}
	/**
	 * 收货完成 确认操作
	 * @param ids
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/doReceive")
	public void doReceive(HttpSession httpSession, String ids,HttpServletResponse response) throws Exception {
		
		//获取当前操作人
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		String[] arr = ids.split(",");
		
		for (String s : arr) {
			Receive param = new Receive();
			
			param.setId(Long.valueOf(s));
			param.setState(3);
			//获取当前时间
			param.setSureDate(DateUtil.dateFormat3());
			//获取当前操作人
			param.setSureName(userName);
			
			Integer affact = ReceiveService.update(param);
			
			ResponseUtil.write(response, affact);
		}
	}
	
	/**
	 * 更新状态
	 * @param ids
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/updateState")
	public void updateState(HttpSession httpSession, String ids,HttpServletResponse response) throws Exception{
		//获取当前操作人
		ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
		String userName = su.getUserName();
		
		Integer count = 0;
		String[] split = ids.split(",");
		
		for (String s : split) {
			long id = Long.parseLong(s);
			Receive param = new Receive();
			param.setId(id);
			param.setState(1);
			
			//获取当前时间
			param.setReceiveDate(DateUtil.dateFormat3());
			//获取当前操作人
			param.setReceiveName(userName);
			
			count = ReceiveService.update(param);
		}
		response.getWriter().print(count);
	}
	
	//-------------------------------------------------app---------------------------------------------------------------
	
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	 * @throws Exception 
	*/
	@RequestMapping("/receiving")
	@ResponseBody
	public void receiving(Receive param,HttpServletResponse response) throws Exception {
		param.setState(0);
		List<Receive> list = ReceiveService.queryAllByMution(param);
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count>0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 修改收货单状态
	 * @param id
	 * @param response
	 */
	@RequestMapping("/updateStatus")
	public void updateStatus(Long id ,HttpServletResponse response, HttpSession httpSession){
		Receive queryById = ReceiveService.queryById(id);
		int i = 0;
		if(queryById != null){
			//获取当前操作人
			ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
			String userName = su.getUserName();
			queryById.setConfirmorDate(DateUtil.dateFormat3());
			queryById.setConfirmor(userName);
			queryById.setState(1);
			i = ReceiveService.update(queryById);
		}
		try {
			ResponseUtil.write(response, i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/list1")
	public void list1(Receive param,HttpServletResponse response) throws Exception{
		/*
		 * 条件分页查询内容
		 */
		List<Receive> list = ReceiveService.queryAllByMution1(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = ReceiveService.selectCountByMution1(param);
		/*
		 * 转为json数据传至页面
		 */
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
		//创建result
		JSONObject result = new JSONObject();
		//转json数据
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		//添加入result
		result.put("code", 0);
		result.put("data", jsonArray);
		result.put("count", total);
		ResponseUtil.write(response, result);
	}
	/**
     * 导出Excel
     * @param response
     * @throws Exception
     */
    @RequestMapping("/doExportall")
	@ResponseBody
    public void doExportall(Receive param,HttpSession session,HttpServletResponse response) throws Exception{
    	//LZ新增仓库id字段
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		param.setWarehouse_id(warehouse_id);
    	param.setLimit(10000);
    	param.setPage(1);
    	param.setIsSimple("0");
        List<Receive> Receives = ReceiveService.findPageByMution(param);
        List<List<String>> lists = zhuanlist(Receives);
        ExcelUtils.export("入库单数据",namess(), response, lists);
    }

    public List<String> namess() {
        List<String> list = new ArrayList<>();
        list.add("NO");
        list.add("收货单编号");
        list.add("送货单编号");
        list.add("供应商");
        list.add("发货人");
        list.add("发货日期");
        list.add("收货人");
        list.add("收货日期");
        list.add("确认人");
        list.add("确认日期");
        list.add("状态");
        list.add("是否取消");
        list.add("取消人");
        list.add("取消时间");
        list.add("恢复人");
        list.add("恢复时间");
        list.add("备注");
        return list;
    }

    /**
     * 根据导出数据表头把List<cuser>转List<List<String>>
     * @param materiels
     * @return
     */
    public List<List<String>> zhuanlist (List<Receive> Receives){
        List<List<String>> lists = new ArrayList<>();
           for (Receive receive : Receives) {
		    List<String> list = new ArrayList<>();
             list.add(String.valueOf(receive.getId()));
             list.add(receive.getReceiveNumber());
             list.add(receive.getSendNumber());
             list.add(receive.getSendCompany());
             list.add(receive.getSendName());
             list.add(receive.getSendDate());
             list.add(receive.getReceiveName());
             list.add(receive.getReceiveDate());
             list.add(receive.getConfirmor());
             list.add(receive.getConfirmorDate());
             
             if(receive.getState()==0) {
            	 
             list.add("未收货");
             }else {
            	 list.add("已收货");
             }
             if(receive.getFlag().equals("0")) {
            	 
             list.add("已取消");
             }else if(receive.getFlag().equals("1")) {
            	 
             list.add("已恢复");
             }else {
                	 list.add("未操作");
            }
             list.add(receive.getCancellation());
             list.add(receive.getCancellation_time());
             list.add(receive.getRestorer());
             list.add(receive.getRestorer_time());
             list.add(receive.getRemark());
             lists.add(list);
             List<String> listd = new ArrayList<>();
             listd.add("收货单编号为"+receive.getReceiveNumber()+"的收货单详情表");
             lists.add(listd);
             List<String> listn = new ArrayList<>();
             listn.add("序号");
            
             listn.add("SAP/QAD");
             listn.add("中文名称");
             listn.add("零件号");
             listn.add("包装数量");
             listn.add("是否拆箱");
             listn.add("条码类型");
             listn.add("批次");
             listn.add("发货箱数(箱)");
             listn.add("发货单数(个)");
             listn.add("发货总数(个)");
             listn.add("收货总数(个)");
             lists.add(listn);
             ReceiveDetail param1=new ReceiveDetail();
             param1.setLimit(10000);
		     param1.setPage(1);
         	 param1.setReceiveNumber(receive.getReceiveNumber());
         	 List<ReceiveDetail> listds = ReceiveDetailService.findPageByMution(param1);
            for (ReceiveDetail detail : listds) {
            	 List<String> list1 = new ArrayList<>();
            	 list1.add(String.valueOf(detail.getId()));
              
                 list1.add(detail.getMateriel_num());
                 list1.add(detail.getMateriel_name());
                 list1.add(detail.getBrevity_num());
                 list1.add(detail.getPacking_quantity());
                 if(detail.getIs_devanning().equals(0)) {
                	 list1.add("是");
                 }else {
                	 list1.add("否");
                	 
                 }
                 if(detail.getBarcode_type().equals("0")) {
                	 
                     list1.add("精准码");
                     }else if(receive.getFlag().equals("1")) {
                    	 
                     list1.add("产品码");
                     }else {
                        	 list1.add("简码");
                    }
                
                 list1.add(detail.getPici());
                 list1.add(String.valueOf(detail.getSendNum()));
                 list1.add(String.valueOf(detail.getSingleNum()));
                 list1.add(String.valueOf(detail.getTotalNum()));
                 list1.add(String.valueOf(detail.getCodeNum()));
                 lists.add(list1);
                 list1 = null;
			}
            list = null;
        }
        return lists;
    }

	/**
	 * 查询所有识别号
	 * @param response
	 * @param session
	 */
	@RequestMapping("/queryAllIdentifyingcode")
	public void queryAllIdentifyingcode(HttpServletResponse response, HttpSession session) {
		Long warehouse_id = (Long) session.getAttribute("warehouse_id");
		List<Identifyingcode> identifyingcodeList = ReceiveService.queryAllIdentifyingcode(warehouse_id);
		JSONArray jsonArray = JSONArray.fromObject(identifyingcodeList);
		if (identifyingcodeList.size() > 0) {
			try {
				ResponseUtil.write(response, jsonArray);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 导入Excel t 添加导入功能，单个单子导入 2019-11-20
	 * @param file Excel
	 * @param request
	 * @param response
	 */
    @RequestMapping("/uplodeFile")
    public void importor(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response,HttpSession httpSession) {
        
        //获取仓库id
        Long wareHouseId = BaseUtils.getSession();
        int flag = 0;
        //判断仓库id是否为空
        if(wareHouseId != null) {
        	//根据仓库id查询仓库信息
        	Warehouse warehouse = warehouseService.queryWarehouse(wareHouseId);
        	logger.info("收货单的导入Excel");
        	//获取当前操作人
        	ZcSysUserEntity su = (ZcSysUserEntity)httpSession.getAttribute("user");
        	String userName = su.getUserName();
        	
        	String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
        	File newFile=new File(savePath);
        	//通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        	try {
        		file.transferTo(newFile);
        	} catch (IOException e) {
        		e.printStackTrace();
        	}
        	//取文件后缀
        	String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
        	System.out.println(subfix);
        	List<List<String>> lists = new ArrayList<>();
        	//获取导入行数
        	int num = 6;
        	if(subfix.equals("xls")){
        		try {
        			lists = ExcelUtils.readXls(savePath, request, num);
        		} catch (IOException e) {
        			e.printStackTrace();
        		}
        	}else if(subfix.equals("xlsx")){
        		try {
        			lists = ExcelUtils.readXlsx(savePath, request,num);
        		} catch (IOException e) {
        			e.printStackTrace();
        		}
        	}else{
        		try {
        			response.getWriter().print("0");
        		} catch (IOException e) {
        			e.printStackTrace();
        		}
        	}
			if (lists != null && lists.size() > 1 
					&& lists.get(0) != null && lists.get(0).size() >= 6 
					&& null != lists.get(0).get(0) && !"".equals(lists.get(0).get(0))  
					&& null != lists.get(0).get(1) && !"".equals(lists.get(0).get(1))
					&& null != lists.get(0).get(3) && !"".equals(lists.get(0).get(3))) {
        		//成功标识
        		flag = 1;
        		List<String> list = new ArrayList<>();
    			list= lists.get(0);
    			Receive receive = new Receive();
    			//收货单号
    			receive.setReceiveNumber(list.get(0));
    			receive.setWarehouse_id(wareHouseId);
    			List<Receive> receiveOld = ReceiveService.queryAllByMution(receive);
    			//供应商
    			Customer customer = new Customer();
    			customer.setCustomer_name(list.get(1));
    			customer.setCustomer_type("0");
    			customer.setWarehouse_id(wareHouseId);
    			List<Customer> customers = othersService.customerQueryAllByMution(customer);
    			//有对应供应商且单号不重复
    			if(customers.size() > 0 && receiveOld.size() == 0){
    				receive.setSendCompany(customers.get(0).getId()+"");
    				receive.setSendName(customers.get(0).getCustomer_name());
    				//发货日期
    				receive.setSendDate(list.get(2));
    				//送货单号
    				receive.setSendNumber(list.get(3));
    				receive.setrName(warehouse.getCharger());
    				receive.setRtel(warehouse.getChargertel());
    				//识别码
    				if(null != list.get(4) && !"".equals(list.get(4))){
    					Identifyingcode identifyingcode = new Identifyingcode();
    					identifyingcode.setIdentifying_code(list.get(4));
    					identifyingcode.setWarehouse_id(wareHouseId);
    					List<Identifyingcode> identifyingcodes = ReceiveService.identifyingcodeQueryAllByMution(identifyingcode);
						if(identifyingcodes.size() > 0){
							receive.setIdentifyingcode_id(identifyingcodes.get(0).getId());
						}
    				}
    				//备注
    				receive.setRemark(list.get(5));
    				
    				receive.setCreateDate(DateUtil.dateFormat3());
    				receive.setCreateName(userName);
    				receive.setState(0);
    				receive.setIsSimple("0");
    				Long id = ReceiveService.insert(receive);
    				if(null == id || id <= 0){
    					//没有找到对应供应商
        				flag = 0;
    				}
    			}else{
    				//没有找到对应供应商
    				flag = 0;
    			}
    			if(flag == 1){
    				ReceiveDetail receiveDetail = new ReceiveDetail();
    				receiveDetail.setReceiveNumber(receive.getReceiveNumber());
    				for (int i = 2; i < lists.size(); i++) {
    					List<String> list2 = lists.get(i);
    					if(null != list2.get(0) && !"".equals(list2.get(0))) {
    						//物料SAP/QAD
    						//List<Materiel> ms=materielService.queryMaterielBybnum(list.get(0));
    						Map<String, Object> map = new HashMap<>();
    						map.put("limit", 10);
    						map.put("page", 1);
    						map.put("materielName", "");
    						map.put("key0", list2.get(0));
    						map.put("customerId", customers.get(0).getId());
    						//map.put("warehouseId", Long.parseLong(warehouseId));
    						map.put("source", 1);
    						List<Materiel> ms = cancellingStockDetailService.listPageMaterielByCustomerIdAndWarehouseId(map);
    						if(ms.size()>0) {
    							receiveDetail.setMid(ms.get(0).getId());
    							//批号	
    							receiveDetail.setPici(list2.get(1));
    							//包装件数	
    							//receiveDetail.setSendNum(StringUtil.strNum(list2.get(2)));
    							receiveDetail.setTotalNum(StringUtil.strNum(list2.get(2)));
    							//计划编号	
    							receiveDetail.setReceiveNum(list2.get(3));
    							//合同号	
    							receiveDetail.setRemark(list2.get(4));
    							//线重
    							receiveDetail.setRcode(Float.parseFloat(list2.get(5)));
    							/**********irving新增start**********/
    							//插入数据之前先判断有没有同批次的同种物料，有的话则合并
    							
    							/**********irving新增end**********/
    							Long affact = ReceiveDetailService.insert(receiveDetail);
    							ms = null;
    							list2 = null;
    							if(null == affact || affact <= 0){
    								//没有找到对应供应商
    								flag = 0;
    								break;
    							}
    						}else{
    							flag = 0;
    							ms = null;
    							list2 = null;
    							break;
    						}
    					}else{
							flag = 0;
							list2 = null;
							break;
						}
    				}
    			}
        	}
        }
        try {
            response.getWriter().print(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
